import {
	request
} from '@/js_sdk/uni-admin/request.js'

export default {
	namespaced: true,
	state: {
		inited: false,
		navMenu: [],
		active: '',
		adminShop: {}, //当前管理店铺
		adminShopList: [], //自己管理的所有店铺
		appName: process.env.VUE_APP_NAME || ''
	},
	mutations: {
		SET_ADMIN_SHOP_LIST(state, shop) {
			state.adminShopList = shop;
			/* if (!state.adminShop.id && shop.length > 0) {
				state.adminShop = {
					...shop[0]
				}
			} */
		},
		SET_ADMIN_SHOP(state, shop) {
			state.adminShop = shop;
			uni.setStorage({
				key: "admin_shop_info",
				data: shop
			})
		},
		SET_APP_NAME: (state, appName) => {
			state.appName = appName
		},
		SET_NAV_MENU: (state, navMenu) => {
			state.inited = true
			state.navMenu = navMenu
		},
		TOGGLE_MENU_ACTIVE: (state, url) => {
			state.active = url
		}
	},
	actions: {
		init({
			commit
		}) {
			let shop = uni.getStorageSync("admin_shop_info");
			if (shop) {
				console.log("store init shop", shop)
				commit('SET_ADMIN_SHOP', shop);
			}
			request('shop/init')
				.then(res => {
					const {
						shops,
						webConfig
					} = res
					commit('SET_ADMIN_SHOP_LIST', shops)
					uni.setStorageSync("webConfig", webConfig)
					if (shops.length > 0) {
						let isSetShop = false;
						for (let s of shops) {
							//设置上次选择的店铺
							if (s.id == shop.id) {
								commit('SET_ADMIN_SHOP', s)
								isSetShop = true;
							}
						}
						//默认第一个店铺
						if (!isSetShop) {
							commit('SET_ADMIN_SHOP', shops[0])
						}
					}
				})
			return request('app/init')
				.then(res => {
					const {
						navMenu,
						userInfo
					} = res
					commit('SET_NAV_MENU', navMenu)
					commit('user/SET_USER_INFO', userInfo, {
						root: true
					})
				})
		},
		setAppName({
			commit
		}, appName) {
			commit('SET_APP_NAME', appName)
		},
		changeMenuActive({
			commit
		}, url) {
			commit('TOGGLE_MENU_ACTIVE', url)
		}
	}
}
